#include "Mutex.hpp"
#include <string>
#include <stdio.h>
#include <unistd.h>
using namespace MutexModule;

int ticket = 1000;

class ThreadData
{
public:
    ThreadData(const std::string &name, Mutex &lock)
        : _name(name),
          _lock(&lock)
    {
    }
    ~ThreadData()
    {
    }
    std::string _name;
    Mutex *_lock;
};

void *route(void *arg)
{
    ThreadData *td = static_cast<ThreadData *>(arg);
    while (1)
    {
        LockGuard guard(td->_lock);
        if (ticket > 0)
        {
            usleep(1000);
            printf("%s: %d\n", td->_name.c_str(), ticket);
            ticket--;
        }
        else
        {
            break;
        }
        
        // usleep(123);
    }

    return nullptr;
}

int main()
{
    Mutex lock;

    pthread_t t1, t2, t3;

    ThreadData td1("Thread 1", lock);
    pthread_create(&t1, nullptr, route, &td1);

    ThreadData td2("Thread 2", lock);
    pthread_create(&t2, nullptr, route, &td2);

    ThreadData td3("Thread 3", lock);
    pthread_create(&t3, nullptr, route, &td3);

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);

    return 0;
}
